<template>
    <div class='container'>
        <input type="file" ref="upload_file" accept=".xls,.xlsx" class="upload_file" @change="readExcel($event)" />
        <button @click="downLoad">导出</button>
    </div>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
export default {
    data() {
        return {
            upload_file: "",
            lists: [],

        };
    },
    created() {

    },
    methods: {
        readExcel(e) {
            // 读取表格文件
            let that = this;
            const files = e.target.files;
            if (files.length <= 0) {
                return false;
            } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
                this.$message({
                    message: "上传格式不正确，请上传xls或者xlsx格式",
                    type: "warning",
                });
                return false;
            } else {
                // 更新获取文件名
                that.upload_file = files[0].name;
            }
            const fileReader = new FileReader();
            fileReader.onload = (ev) => {
                console.log('----------', ev);
                // try {
                const data = ev.target.result;
                const workbook = XLSX.read(data, {
                    type: "binary",
                });
                const wsname = workbook.SheetNames[0]; //取第一张表
                console.log('-----1', XLSX);
                console.log('------2', wsname);
                console.log('------3', workbook);
                const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
                that.lists = [];
                //console.log(ws);
                // 从解析出来的数据中提取相应的数据
                ws.forEach((item) => {
                    //读出来的excel表里的数据放在lists数组里
                    that.lists.push({
                        code: item["编号"],
                        name: item["姓名"],
                        gender: item["性别"],
                        age: item["年龄"],
                        card: item["身份证号"],
                    });
                });
                // 给后端发请求
                this.submit_form();
                // } catch (e) {
                //     console.log('========');
                //     return false;
                // }
            };
            fileReader.readAsBinaryString(files[0]);
        },


        submit_form() {
            //我这里是将lists进行循环遍历，然后分别调接口单个写入数据库创建的
            let that = this;
            let bar = 0, //导入成功数
                foo = 0, //导入失败数
                count = 0; //导入的总数
            this.lists.forEach((e, i) => {
                let url = 接口URL;
                this.$axios.post(url, this.$qs.stringify(e)).then((res) => {
                    count++;
                    if (res.code == 1) {
                        bar++;
                    } else {
                        foo++;
                    }
                    if (count == this.lists.length) {
                        alert(`共${that.lists.length}条数据,导入成功数：${bar},导入失败数:${foo}`);
                        window.location.reload();
                    }
                });
            });
        },
        downLoad() {
            let arr = [{
                sno: 1000,
                username: "司大帅",
                gender: "男",
                age: 21,
                card: "412345678987654321"
            }, {
                sno: 1001,
                username: "司小帅",
                gender: "男",
                age: 22,
                card: "41234567898765432X"
            }]
            import("../vendor/Export2Excel").then((excel) => {
                //tHeader 为导出后的表头
                const tHeader = ["编号", "姓名", "性别", "年龄", "身份证号"];
                const filterVal = ["sno", "username", "gender", "age", "card"];
                const list = arr;
                const data = this.formatJson(filterVal, list);
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: "文件名",
                    autoWidth: true,
                    bookType: "xlsx",
                });
            });
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map((v) =>
                filterVal.map((j) => {
                    if (j === "timestamp") {
                        return parseTime(v[j]);
                    } else {
                        return v[j];
                    }
                })
            );
        },

    },
    components: {

    },
};
</script>

<style lang='scss' scoped>

</style>

